package com.forum.module.system.controller.captcha;

import cn.hutool.captcha.LineCaptcha;
import com.forum.framework.common.constant.CacheConstants;
import com.forum.framework.common.exception.util.ServiceExceptionUtils;
import com.forum.framework.common.pojo.DataResult;
import com.forum.framework.redis.core.RedisCache;
import com.forum.module.system.util.uuid.IdUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.forum.module.system.enums.ErrorCodeConstants.*;

/**
 * 验证码控制器
 *
 * @author zihan.ouyang
 */
@Tag(name = "管理后台 - 验证码")
@RestController("adminCaptchaController")
@RequestMapping("/system/captcha")
public class CaptchaController {
    private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);
    private final RedisCache redisConfig;

    public CaptchaController(RedisCache redisConfig) {
        this.redisConfig = redisConfig;
    }

    @GetMapping("/get")
    @Operation(summary = "获取验证码")
    public Map<String, Object> getCaptcha() {
        LineCaptcha lineCaptcha = new LineCaptcha(150, 40, 4, 4);

        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captchaCode = lineCaptcha.getCode();

        redisConfig.set(verifyKey, captchaCode, 60);
        Map<String, Object> result = new HashMap<>();
        result.put("uuid", uuid);
        result.put("img", lineCaptcha.getImageBase64Data());
        return result;
    }

    @GetMapping("/check")
    @Operation(summary = "验证验证码")
    public DataResult<Boolean> checkCaptcha(@RequestParam("username") String username, @RequestParam("code") String code, @RequestParam("uuid") String uuid) {
        boolean captchaEnabled = true;
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
            String captcha = (String) redisConfig.get(verifyKey);
            if (captcha == null) {
                logger.info("验证码已失效, {}", username);
                throw ServiceExceptionUtils.exception(USER_LOGIN_CAPTCHA_EXPIRE);
            }
            redisConfig.delete(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
                logger.info("验证码不正确, {}", username);
                throw ServiceExceptionUtils.exception(USER_LOGIN_CAPTCHA_ERROR);
            }
        }
        return DataResult.success(true);
    }

}
